package com.seven.springboot.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


@SuppressWarnings({ "unused", "restriction" })
public class ImageUtils {

	
	public static boolean generateImage(String imgStr, String path, String fileName) {
		if (StringUtils.isEmpty(imgStr) || StringUtils.isEmpty(path)) {
			return false;
		}
		File file = new File(path);
		if(!file.exists()) {
			file.mkdirs();
		}
		String filePath = path +File.separator + fileName;
		BASE64Decoder decoder = new BASE64Decoder();
		OutputStream out = null;
		try {
			//解密
			byte[] b = decoder.decodeBuffer(imgStr);
			//处理数据
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			out = new FileOutputStream(filePath);
			out.write(b);
			out.flush();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
	
	public static String getImageStr(String imgFile) {
	    InputStream inputStream = null;
	    byte[] data = null;
	    try {
	        inputStream = new FileInputStream(imgFile);
	        data = new byte[inputStream.available()];
	        inputStream.read(data);
	        inputStream.close();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    // 加密
	    BASE64Encoder encoder = new BASE64Encoder();
	    return encoder.encode(data);
	}
	
	public static void main(String[] args) {
		String path = "e:\\qyi\\";
		String imageStr = "";
		File file = new File(path);
		/*if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/
		generateImage(imageStr,path ,"bb.jpg");
		
//		String str = getImageStr("e:\\qyi\\222.jpg");
//		System.out.println(str);
	}
}
